#!/usr/bin/python
import sys,os,string
#import Tkinter
#import glob
from Foundation import NSNumber
from AppKit     import NSImage
from QTKit      import *


def render(folder,frames,frameRate):
    print "render images in ", folder
    outfile = string.join([os.path.splitext(os.path.abspath(folder))[0],"mov"],".")
    
    print "export to ", outfile
    
    time = QTMakeTime(frameRate,600)
    attrs = {QTAddImageCodecType: "jpeg", QTAddImageCodecQuality: NSNumber.numberWithLong_(codecHighQuality)}
    mov, err = QTMovie.alloc().initToWritableFile_error_(outfile,None)
    if mov is None:
        errmsg = "Unable to create movie file: %s" % (outfile)
        raise IOError, errmsg
    for frame in frames:    
        imgPath = folder+frame
        print frame
        img = NSImage.alloc().initWithContentsOfFile_(imgPath)
        mov.addImage_forDuration_withAttributes_(img, time, attrs)
        mov.updateMovieFile()  
    #mov.play()
    #mov.dealloc()



####Main Loop######

if len(sys.argv) != 3:
    print "python myStopMotion path frameRate"
else:
    #print sys.argv[1]
    folder    = sys.argv[1]
    frameRate = int(sys.argv[2])
    frames = [file for file in os.listdir(folder) if file.endswith(".jpeg")]
    print frames
    render(folder,frames,frameRate)

    #render(folder)  
    #top = Tkinter.Tk()
    #top.mainloop()  
